package com.yunquan.ohana.ui.launcher

import android.app.Application
import androidx.lifecycle.LifecycleOwner
import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.base.bus.RxSubscriptions
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.db.DBPhoto
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.entity.EventType
import com.yunquan.ohana.entity.UserEntity
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.ui.bindDevice.BindDeviceActivity
import com.yunquan.ohana.ui.main.MainActivity
import com.yunquan.ohana.utils.L
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.Disposable

class LauncherViewModel(application: Application) : BaseViewModel(application) {

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        // 每次启动都把之前上传中的数据更改成失败
        DBPhoto.instance.updateSendingToFailed()
    }

    override fun onEvent(event: EventEntity) {
        super.onEvent(event)
        if (event.type == EventType.AUTH_FAILED) {
            startActivity(BindDeviceActivity::class.java)
            finish()
        }
    }

    fun getUserInfo() {
        BaseHttp.api.getAppUser()
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<UserEntity>() {
                override fun onSuccess(result: UserEntity?) {
                    super.onSuccess(result)
                    if (result != null) {
                        startActivity(MainActivity::class.java)
                    } else {
                        startActivity(BindDeviceActivity::class.java)
                    }
                    finish()
                }

                override fun onComplete() {
                    super.onComplete()
                }
            })
    }
}